package com.formen.ndk;

import java.io.*;
import java.util.*;

import org.json.*;

import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

import com.facebook.*;
import com.facebook.android.*;

public class FaceBookTest extends Activity {

	private Button mBtnFeed, mBtnLoginout;
	private EditText mEtContent;
	private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;
	
	String m_id, m_name, m_time, m_loca;

	private Session.StatusCallback statusCallback = new SessionStatusCallback();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.p4);
		
		Intent i = getIntent();
		m_id = i.getStringExtra("Id");
		m_name = i.getStringExtra("Name");
		m_time = i.getStringExtra("mTime");
		m_loca = i.getStringExtra("mLoca");
		
		mBtnFeed = (Button) findViewById(R.id.btnFeed);
		mBtnLoginout = (Button)findViewById(R.id.btnLoginout);
		mEtContent = (EditText) findViewById(R.id.etContent);
		
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
		
		Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }

		
		mBtnFeed.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				feed();
			}
		});
		
		updateView();
		

	}
	
	@Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }
	
	@Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);

	}
	
	private void updateView() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
        	TextView welcome = (TextView) findViewById(R.id.welcome);
            welcome.setText("페이스북에 로그인되어 있습니다.");
            mBtnLoginout.setText("Logout");
            mBtnLoginout.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogout(); }
            });
        } else {
        	TextView welcome = (TextView) findViewById(R.id.welcome);
            welcome.setText("로그인 버튼을 눌러주세요");
            mBtnLoginout.setText("Login");
            mBtnLoginout.setOnClickListener(new OnClickListener() {
                public void onClick(View view) { onClickLogin(); }
            });
        }
    }

	private void onClickLogin() {
		Session session = Session.getActiveSession();
		if (!session.isOpened() && !session.isClosed()) {
			session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
		} else {
			Session.openActiveSession(this, true, statusCallback);
		}
		

	}

	private void feed() {
		try {
			Session session = Session.getActiveSession();
			Log.v("Feed Part", "access token : " + session.getAccessToken());
			
			if(session.isOpened()){
				File dir = new File(Environment.getExternalStorageDirectory()+"/E-Profile/"); 
		        dir.mkdirs();
				
				String DIRECTORY_PATH = Environment.getExternalStorageDirectory()+"/E-Profile/ugc.jpg";
	            Bitmap bitmap = BitmapFactory.decodeFile(DIRECTORY_PATH);
	            byte[] data = null;
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();
	            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
	            data = baos.toByteArray();
	            
	            
	            // Check for publish permissions    
	            List<String> permissions = session.getPermissions();
	            if (!isSubsetOf(PERMISSIONS, permissions)) {
	                pendingPublishReauthorization = true;
	                Session.NewPermissionsRequest newPermissionsRequest = new Session
	                        .NewPermissionsRequest(this, PERMISSIONS);
	            session.requestNewPublishPermissions(newPermissionsRequest);
	                return;
	            }
	            String urlPath = "http://ce.sejong.ac.kr/~firebat/uploads/";
	            
				Bundle postParams = new Bundle();

				 postParams.putString("name", m_name);
				 postParams.putString("caption", m_time + " " + m_loca + "에서 만남.");
				 postParams.putString("description", mEtContent.getText().toString());
				 postParams.putString("link", "https://developers.facebook.com/android");
				 postParams.putString("picture", urlPath + m_id + ".png");
				
	            
	            
				
				Request.Callback callback= new Request.Callback() {
		            public void onCompleted(Response response) {
		                JSONObject graphResponse = response
		                                           .getGraphObject()
		                                           .getInnerJSONObject();
		                String postId = null;
		                try {
		                    postId = graphResponse.getString("id");
		                } catch (JSONException e) {
		                    Log.i("JSON Part",
		                        "JSON error "+ e.getMessage());
		                }
		                FacebookRequestError error = response.getError();
		                if (error != null) {
		                    Toast.makeText(FaceBookTest.this
		                    		.getApplicationContext(),
		                         error.getErrorMessage(),
		                         Toast.LENGTH_SHORT).show();
		                    } else {
		                        Toast.makeText(FaceBookTest.this
		                             .getApplicationContext(), 
		                             MainActivity.user_name + "님의 담벼락에 올라갔어요.",
		                             Toast.LENGTH_LONG).show();
		                }
		            }
		        };
		        
		        Request request = new Request(Session.getActiveSession(), "me/feed", postParams, 
	                    HttpMethod.POST, callback);
		        RequestAsyncTask task = new RequestAsyncTask(request);
		        task.execute();
			}
			else{
				TextView welcome = (TextView) findViewById(R.id.welcome);
				welcome.setText("실패");
			}

			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
	    for (String string : subset) {
	        if (!superset.contains(string)) {
	            return false;
	        }
	    }
	    return true;
	}

	private void onClickLogout() {
		Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
        }
	}

	private class SessionStatusCallback implements Session.StatusCallback {
		public void call(Session session, SessionState state, Exception exception) {
            updateView();
        }
	}

}